package com.interrupt.twophasetermination;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 二阶段终止
 */
@Slf4j
public class TwoPhaseTermination implements Runnable {


    @Override
    public void run() {

        // 注意：此方法获取线程是否被打断之后，会顺带清除中断标志
        boolean interrupted = Thread.interrupted();

        while (!Thread.currentThread().isInterrupted()) {

            log.debug("发送此程序的运行时统计信息");

            try {
                // sleep() 方法抛出 InterruptedException 时，会顺便清除 中断标志位
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                // 重新设置中断标记为 true
                Thread.currentThread().interrupt();
                log.debug("睡眠时被终止，现重新设置中断标志");
                e.printStackTrace();
            }
        }

        log.debug("安全的退出..");

    }


    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new TwoPhaseTermination(), "自动上报程序统计信息的守护线程");


        thread.start();


        TimeUnit.SECONDS.sleep(5);

        log.debug("现在准备中断{}",thread.getName());
        thread.interrupt();

    }
}
